package com.iddaa.core.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

@Aspect
@Component("auditAspect")
public class AuditAspect {

	private int threshold = 100;

	private static final Logger logger = LoggerFactory.getLogger(AuditAspect.class);

	@Around("inServiceLayer()")
	public Object track(ProceedingJoinPoint joinPoint) throws Throwable {
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		Object retVal = joinPoint.proceed();
		stopWatch.stop();
		Object[] params = joinPoint.getArgs();
		long diff = stopWatch.getTotalTimeMillis();
		if (diff > threshold) {
			logger.info("Processing on {}.{}({}) takes {} ms", new Object[] { joinPoint.getTarget().getClass().getSimpleName(), joinPoint.getSignature().getName(), params, diff });
		} else {
			logger.debug("Processing on {}.{}({}) takes {} ms", new Object[] { joinPoint.getTarget().getClass().getSimpleName(), joinPoint.getSignature().getName(), params, diff });
		}
		return retVal;
	}

	@Pointcut("execution(* com.iddaa.core.dao..*.*(..))")
	public void inDAOLayer() {
	}

	@Pointcut("execution(* com.iddaa.core.service..*.*(..))")
	public void inServiceLayer() {
	}

}
